{% extends "base.html" %}

{% block title %}Cart - PinCaiCai 2.0{% endblock %}

{% block content %}
<div class="container mt-4">
    <h2>Cart</h2>
    <div id="cart-container">
        <!-- Cart content will be dynamically loaded via JavaScript -->
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    loadCart();
});

function loadCart() {
    fetch('/api/cart')
        .then(response => response.json())
        .then(data => {
            const container = document.getElementById('cart-container');
            if (data.error && data.error.includes('login')) {
                container.innerHTML = '<div class="text-center"><p>Please login first to view cart</p><a href="/login" class="btn btn-primary">Go to Login</a></div>';
                return;
            }
            if (data.items && data.items.length > 0) {
                let total = 0;
                let totalQuantity = 0;
                let html = '<div class="row"><div class="col-md-8">';
                
                data.items.forEach(item => {
                    const product = item.product;
                    const itemTotal = parseFloat(product.price) * item.quantity;
                    total += itemTotal;
                    totalQuantity += item.quantity;
                    
                    html += `
                        <div class="card mb-3">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-md-2">
                                        <div class="d-flex align-items-center justify-content-center" style="height: 80px; background-color: #f8f9fa; font-size: 2rem;">
                                            ${product.emoji || '📦'}
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <h5>${product.name}</h5>
                                        <p class="text-muted">${product.origin || ''}</p>
                                    </div>
                                    <div class="col-md-2">
                                        <p class="fw-bold">¥${product.price}</p>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="input-group cart-input-group">
                                            <button class="btn btn-outline-secondary" onclick="updateQuantity(${item.cart_id}, ${item.quantity - 1})">-</button>
                                            <input type="number" class="form-control cart-quantity-input" value="${item.quantity}" min="1" max="${product.stock}" onchange="updateQuantity(${item.cart_id}, this.value)">
                                            <button class="btn btn-outline-secondary" onclick="updateQuantity(${item.cart_id}, ${item.quantity + 1})">+</button>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <p class="fw-bold">¥${itemTotal.toFixed(2)}</p>
                                        <button class="btn btn-danger btn-sm" onclick="removeFromCart(${item.cart_id})">Remove</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                html += '</div><div class="col-md-4">';
                html += `
                    <div class="card">
                    <div class="card-header">
                        <h5>Order Summary</h5>
                    </div>
                    <div class="card-body">
                        <p>Total Items: ${totalQuantity}</p>
                        <p>Total Amount: <span class="fw-bold text-success">¥${total.toFixed(2)}</span></p>
                        <button class="btn btn-success w-100 mb-2" onclick="checkout()">Checkout</button>
                        <button class="btn btn-outline-danger w-100" onclick="clearCart()">Clear Cart</button>
                    </div>
                    </div>
                `;
                html += '</div></div>';
                
                container.innerHTML = html;
            } else {
                container.innerHTML = '<div class="text-center"><p>Cart is empty</p><a href="/all" class="btn btn-primary">Go Shopping</a></div>';
            }
        })
        .catch(error => {
            console.error('Error loading cart:', error);
            document.getElementById('cart-container').innerHTML = '<div class="text-center"><p>Failed to load cart</p></div>';
        });
}

function updateQuantity(cartItemId, newQuantity) {
    if (newQuantity < 1) {
        removeFromCart(cartItemId);
        return;
    }
    
    fetch(`/api/cart/${cartItemId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            quantity: parseInt(newQuantity)
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.message) {
            loadCart(); // Reload cart
        } else if (data.error && data.error.includes('login')) {
            alert('Please login first before operating cart!');
        } else {
            alert('Update failed: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error updating cart:', error);
        alert('Update failed, please try again');
    });
}

function removeFromCart(cartItemId) {
    if (confirm('Are you sure you want to delete this item?')) {
        fetch(`/api/cart/${cartItemId}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                loadCart(); // Reload cart
            } else if (data.error && data.error.includes('login')) {
                alert('Please login first before operating cart!');
            } else {
                alert('Delete failed: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error removing from cart:', error);
            alert('Delete failed, please try again');
        });
    }
}

function checkout() {
    if (confirm('Are you sure you want to checkout?')) {
        fetch('/api/orders', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({})
        })
        .then(response => response.json())
        .then(data => {
            if (data.message && data.message.includes('success')) {
                alert('Order created successfully!');
                window.location.href = '/orders';
            } else if (data.error && data.error.includes('login')) {
                alert('Please login first before purchasing!');
            } else {
                alert('Create order failed: ' + (data.error || data.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error creating order:', error);
            alert('Create order failed, please try again');
        });
    }
}

function clearCart() {
    if (confirm('Are you sure you want to clear the cart? This action cannot be undone!')) {
        fetch('/api/cart', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.message && data.message.includes('clear')) {
                alert('Cart cleared!');
                loadCart(); // Reload cart
            } else if (data.error && data.error.includes('login')) {
                alert('Please login first before operating cart!');
            } else {
                alert('Clear failed: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error clearing cart:', error);
            alert('Clear failed, please try again');
        });
    }
}
</script>
{% endblock %}
